package com.itdct.onflow.core.util

import cn.hutool.core.util.ReflectUtil
import cn.hutool.core.util.StrUtil


/**
 * @author Zhouwx
 * @version 1.0
 * @date 2023/11/23 14:10:41
 * @description
 */
class BeanToSql<T>(private val data: MutableList<T?>) {
    private var clazz: Class<T?>? = null

    fun beanToSql(tableName: String): String {
        if (data.isEmpty()) {
            return ""
        }
        val t = data.get(0)
        clazz = t!!.javaClass as Class<T?>

        val columnNames = ArrayList<String>()
        val fields = ReflectUtil.getFields(clazz)
        for (field in fields) {
            field.setAccessible(true)
            val fieldName = field.getName()
            val underlineCase = "`" + StrUtil.toUnderlineCase(fieldName) + "`"
            columnNames.add(underlineCase)
        }

        val columnString = "(" + columnNames.joinToString(", ") + ")"
        val stringBuilder = StringBuilder()
        stringBuilder.append("insert into `")
            .append(tableName)
            .append("` ")
            .append(columnString)
            .append(" values ")

        val valuesStrings = ArrayList<kotlin.String?>()
        for (datum in data) {
            val values = ArrayList<kotlin.String?>()
            for (field in fields) {
                var o: Any? = null
                try {
                    o = field.get(datum)
                } catch (e: IllegalAccessException) {
                    e.printStackTrace()
                }
                if (o == null) {
                    values.add("null")
                } else {
                    var s: kotlin.String? = o.toString()
                    s = "'" + s + "'"
                    values.add(s)
                }
            }
            val itemString = "(" + values.joinToString(", ") + ")"
            valuesStrings.add(itemString)
        }
        val resultValueString = valuesStrings.joinToString(", ")
        stringBuilder.append(resultValueString)
            .append(";")

        return stringBuilder.toString()
    }
}
